const LoginLogModel = require('@/models/login_log.model')
const JsonResult = require('@/utils/httpResponse.unit')
const log = require('@/utils/logo.unit')

class LoginLogController {
  /**
   * search logs by userId
   * @param {*} req
   * @param {*} response
   */
  async findLogList (req, response) {
    try {
      const { pageNo = 1, pageSize = 20 } = req.query
      const userId = req.sessionuser.id
      const data = await LoginLogModel.find(userId, Number(pageNo), Number(pageSize))
      JsonResult.success({
        req,
        response,
        data,
        message: '查询登录日志成功'
      })
    } catch (error) {
      JsonResult.fail({ req, response, error, message: '查询失败' })
    }
  }

  /**
   * generate login log
   * @param {*} userId
   * @param {*} ip
   * @param {*} address
   * @param {*} loginType
   */
  async createLog ({ userId, ip, address, loginType }) {
    try {
      await LoginLogModel.add({ userId, ip, address, loginType })
    } catch (error) {
      const ERRLOG = {
        userId,
        ip,
        address
      }
      log.logger.error(error || JSON.stringify(ERRLOG))
    }
  }
}

module.exports = new LoginLogController()
